import cherrypy
from Cheetah.Template import Template
from cherrypy.lib import httptools
import dailyspents.util as util
from GenericView import GenericView
from dailyspents.model.Category import Category
from dailyspents.model.Payment import Payment
from os.path import join

QUERY_BY_CATEGORY = 'byCategory'
QUERY_BY_PAYMENT = 'byPayment'

class MainView(GenericView):
    
    def __init__(self):
        GenericView.__init__(self)
    
    @cherrypy.expose
    def index(self, message=None, errorMessage=None):
        
        GenericView.index(self, message, errorMessage)
        
        spents = self.spentController.getByOffsetLimit(0, 
                                self.user.settings.numberOfShownSpent)
        
        self.nameSpace['spents'] = spents
        cherrypy.session['spents'] = spents
        self.nameSpace['totalOfSpents'] = self.spentController.getTotal()
        
        if len(spents) > 0:
            self.nameSpace['contextMenu'].append(('Show statistics', 
                    '/spent/makeStatistics'))
        
        return Template(file=join(util.HTMLPATH, "main.html"),
                        searchList=[self.nameSpace]).respond()
    
    @cherrypy.expose
    def deleteItem(self, **kargs):
        try:
            itemType = kargs.get('type', None)
            itemId = int(kargs['id'])
            
            if itemType == "category":
                self.categoryController.deleteById(itemId)
            elif itemType == "payment":
                self.paymentController.deleteById(itemId)
            elif itemType == "local":
                self.localController.deleteById(itemId)
            
            self.message = 'Item was sucefully deleted.'
        except Exception, e:
            print '[an exception occurred] >>>', e
            raise cherrypy.HTTPRedirect("index?errorMessage="+e.message)
            
        raise cherrypy.HTTPRedirect("index?message="+self.message)
    
    @cherrypy.expose
    def renameItem(self, **kargs):
        try:
            itemId = int(kargs['id'])
            itemType = kargs.get('type', None)
            newName = kargs['newName']
            
            if newName == '':
                raise
            
            controller = self.controllers.get(itemType, None)
            
            if controller != None:
                item = controller.getById(itemId)
                item.name = newName
                controller.save(item)
                
            self.message = "Item sucefully renamed."
            
        except Exception, e:
            print '[an exception occurred] >>>', e
            self.message = 'Invalid name.'
            raise cherrypy.HTTPRedirect("index?errorMessage="+self.message)
            
        raise cherrypy.HTTPRedirect("index?message="+self.message)
    
    @cherrypy.expose
    def selectByCategory(self, **kargs):
        id = int(kargs.get('catId', 0))
        category = self.categoryController.getById(id)
        spents = self.spentController.getByCategory(category, 0, 
                                        self.user.settings.numberOfShownSpent)
        
        self.nameSpace = self.makeCommonNamespace()
        self.nameSpace['spents'] = spents
        cherrypy.session['spents'] = spents
        self.nameSpace['query'] = QUERY_BY_CATEGORY
        self.nameSpace['id'] = id
        self.nameSpace['totalOfSpents'] = self.spentController.getTotalByCategory(category)
        
        self.makeContextMenu()
        
        return Template(file=join(util.HTMLPATH, "main.html"),
                        searchList=[self.nameSpace]).respond()
    
    @cherrypy.expose
    def selectByPayment(self, **kargs):
        id = int(kargs.get('paymentId', 0))
        payment = self.paymentController.getById(id)
        spents = self.spentController.getByPayment(payment, 0, 
                                        self.user.settings.numberOfShownSpent)
        
        self.nameSpace = self.makeCommonNamespace()
        
        self.nameSpace['spents'] = spents
        cherrypy.session['spents'] = spents
        self.nameSpace['query'] = QUERY_BY_PAYMENT
        self.nameSpace['id'] = id
        self.nameSpace['totalOfSpents'] = self.spentController.getTotalByPayment(payment)
        
        self.makeContextMenu()
        
        return Template(file=join(util.HTMLPATH, "main.html"),
                        searchList=[self.nameSpace]).respond()
                        
    @cherrypy.expose
    def doNavigation(self, **kargs):
        '''Make the navigation according to user action(query)'''

        offset = kargs.get('offset', 0)
        limit = kargs.get('limit', self.user.settings.numberOfShownSpent)
        
        back = kargs.get('back', False)
        
        if back:
            offset = int(offset) - self.user.settings.numberOfShownSpent
            limit = int(limit) - self.user.settings.numberOfShownSpent
        else:
            offset = int(offset) + self.user.settings.numberOfShownSpent
            limit = int(limit) + self.user.settings.numberOfShownSpent
           
        spents = None
        self.nameSpace = self.makeCommonNamespace()
        #set the context menu
        self.makeContextMenu()
        
        if kargs['query'] == QUERY_BY_CATEGORY:
            catId = int(kargs['id'])
            category = self.categoryController.getById(catId)
            spents = self.spentController.getByCategory(category, offset, limit)
            self.nameSpace['query'] = QUERY_BY_CATEGORY
            self.nameSpace['id'] = catId
            self.nameSpace['totalOfSpents'] = self.spentController.getTotalByCategory(category)
            
        elif kargs['query'] == QUERY_BY_PAYMENT:
            payId = int(kargs['id'])
            payment = self.paymentController.getById(payId)
            spents = self.spentController.getByPayment(payment, offset, limit)
            self.nameSpace['query'] = QUERY_BY_PAYMENT
            self.nameSpace['id'] = payId
            self.nameSpace['totalOfSpents'] = self.spentController.getTotalByPayment(payment)
        else:
            spents = self.spentController.getByOffsetLimit(offset, limit)
            self.nameSpace['totalOfSpents'] = self.spentController.getTotal()
        
        
        self.nameSpace['spents'] = spents
        cherrypy.session['spents'] = spents
        self.nameSpace['offset'] = offset
        self.nameSpace['limit'] = limit
        
        return Template(file=join(util.HTMLPATH, "main.html"),
                        searchList=[self.nameSpace]).respond()